/**
 * 
 */
package org.youisoft.summer.evaluator.function.core;
import org.youisoft.summer.evaluator.InvokeException;
import org.youisoft.summer.evaluator.UnitEnum;
import org.youisoft.summer.evaluator.context.CalContext;
import org.youisoft.summer.evaluator.eval.ExpressionEvaluator;
import org.youisoft.summer.evaluator.function.AbstractFunction;
import org.youisoft.summer.evaluator.operator.Operator;
import org.youisoft.summer.evaluator.operator.base.ClosureOperator;
import org.youisoft.summer.evaluator.unit.Brace;

/**
 * @author zijiang.jl
 *
 */
public class BraceFunction extends AbstractFunction{
	@Override
	public String getName() {
		return Brace.class.getName();
	}
	
	@Override
	public UnitEnum getType() {
		return UnitEnum.brace;
	}

	@Override
	protected boolean checkBraceOperator(int index, Operator<?> operator) {
		if(index==0&&ClosureOperator.class.isAssignableFrom(operator.getClass())) return true;
		return false;
	}
	
	

	@SuppressWarnings("unchecked")
	@Override
	public <C,R,P> Operator<?> doBraceInvoke(final CalContext<C,R,P> context,Operator<?>... operator) throws InvokeException{
		ClosureOperator co=ClosureOperator.class.cast(operator[0]);
		try {
			ExpressionEvaluator<C, R, P> evaluator = ExpressionEvaluator.class.cast(
					Thread.currentThread().getContextClassLoader().loadClass(
							context.getEvaluatorClassName()).newInstance());

		evaluator.setParenthesisClassName(context.getParenthesisClassName());
		evaluator.setBraceClassName(context.getBraceClassName());
		evaluator.setBracketClassName(context.getBracketClassName());
		evaluator.init();
		return evaluator.prepare(co.value()).evaluateOperator(context);
		} catch (Exception e) {
			throw new InvokeException("Closure Operator failure:",e);
			
		}
	}

	@Override
	protected int minOperatorCount() {
		return 1;
	}
	
}
